package com.example.myapplication.part11;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.myapplication.R;

import java.util.List;

public class ChatAdapter extends BaseAdapter {
    private Context context;
    private List<Message> messages;

    public ChatAdapter(Context context, List<Message> messages) {
        this.context = context;
        this.messages = messages;
    }

    @Override
    public int getCount() {
        return messages.size();
    }

    @Override
    public Object getItem(int position) {
        return messages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        Message message = messages.get(position);

        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(context);

            // 根据消息类型加载不同布局
            if (message.isUser()) {
                convertView = inflater.inflate(R.layout.item_user_message, parent, false);
            } else {
                convertView = inflater.inflate(R.layout.item_bot_message, parent, false);
            }

            holder.textView = convertView.findViewById(R.id.messageText);
            holder.timeView = convertView.findViewById(R.id.messageTime);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.textView.setText(message.getText());
        holder.timeView.setText(message.getTime());

        return convertView;
    }

    static class ViewHolder {
        TextView textView;
        TextView timeView;
    }
}